//
//  MXNetworkManager.swift
//  微博
//
//  Created by LoadingMx on 2017/3/27.
//  Copyright © 2017年 LoadingMx. All rights reserved.
//

import UIKit
import AFNetworking

/// Swift 的枚举支持任意数据类型
/// Swift / enum 在OC 中都只是支持整数
enum MXHTTPMethod {
    case GET
    case POST
}
class MXNetworkManager: AFHTTPSessionManager {
    
    /// 在第一次访问时,执行闭包,并且将结果保存在 shared 常量中
    static let shared = MXNetworkManager()
    

    /// 使用一个函数封装 AFN 的 GET / POST 请求
    ///
    /// - Parameters:
    ///   - method: GET / POST
    ///   - URLString: URLStrinG
    ///   - parameters: 参数字典
    ///   - completion: 完成回调[json(字典/数据), 是否成功]
//    func request(method: MXHTTPMethod = .GET, URLString: String, parameters: [String : Any], completion:@escaping (_ json: AnyObject?, _ isSuccess: Bool) -> ()) {
//        
//        // 成功回调
//        let success = { (task: URLSessionDataTask, json: AnyObject?) -> () in
//            completion(json, true)
//        }
//        // 失败回调
//        let failure = { (task: URLSessionDataTask?, error: Error) -> () in
//            // error 通常比较吓人, 错误原因一堆英文]
//            print("网络请求错误 \(error)")
//            completion(nil, false)
//        }
//        
//        if method == .GET{
//
//            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
//        } else {
//            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
//        }
//    }
    
    /// 封装 AFN 的 GET / POST 请求
    ///
    /// - Parameters:
    ///   - method: GET / POST
    ///   - URLString: 请求地址
    ///   - parameters: 参数字典
    ///   - completion: 完成回调, 是否成功
    func request(method: MXHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject], completion: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->()) {
        // 成功回调
        let success = { (task: URLSessionDataTask, json: Any?)->() in
            completion(json as AnyObject, true)
        }
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: Error)->() in
            print("网络请求错误 \(error)")
            completion(nil, false)
        }
        
        if method == .GET {
        get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
        post(URLString, parameters: parameters, progress: nil, success: success , failure: failure)

        }
    }
}
